package com.hys.app.service.open.goods;

import com.hys.app.model.erp.dos.GoodsDO;
import com.hys.app.model.erp.dos.ProductDO;
import com.hys.app.model.erp.dos.ProductStockDO;
import com.hys.app.model.erp.vo.GoodsVO;
import com.hys.app.model.erp.vo.ProductStockVO;
import com.hys.app.model.open.goods.dto.GetGoodsIdsDTO;
import com.hys.app.model.open.goods.dto.GetGoodsStockDTO;
import com.hys.app.service.erp.GoodsManager;
import com.hys.app.service.erp.ProductStockManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hys.app.framework.util.CollectionUtils.convertList;

/**
 * 商品对外接口业务层实现
 *
 * @author 张崧
 * @since 2024-04-08
 */
@Service
@Slf4j
public class GoodsOpenManagerImpl implements GoodsOpenManager {

    @Autowired
    private GoodsManager goodsManager;

    @Autowired
    private ProductStockManager productStockManager;

    @Override
    public List<Long> getGoodsIds(GetGoodsIdsDTO getGoodsIdsDTO) {
        return goodsManager.lambdaQuery()
                .gt(GoodsDO::getId, getGoodsIdsDTO.getLastGoodsId())
                .last("limit " + getGoodsIdsDTO.getLimit())
                .list()
                .stream()
                .map(GoodsDO::getId)
                .collect(Collectors.toList());
    }

    @Override
    public GoodsVO getDetail(Long id) {
        GoodsVO goodsVO = goodsManager.getDetail(id);

        // 查询产品库存
        List<Long> productIds = convertList(goodsVO.getProductList(), ProductDO::getId);
        Map<Long, Integer> stockMap = productStockManager.queryStockNum(null, productIds);
        goodsVO.getProductList().forEach(productVO -> productVO.setStockNum(stockMap.get(productVO.getId())));

        return goodsVO;
    }
}

